<?php
require_once('Extension/Controller/Action.php');

require_once('Zend/Auth.php');

require_once('Zend/Controller/Action/HelperBroker.php');

class Admin_UserController extends Extension_Controller_Action
{
    public function indexAction()
    {
        if (!Zend_Auth::getInstance()->hasIdentity()) {
            $this->_forward('login');
        } else {
            $this->_redirect('/admin');
        }
    }

    public function loginAction()
    {
        $request = $this->getRequest();

        if ($request->isPost()) {

            $posts = $request->getPost();
            $formLogin = self::makeFormUserLogin();

            if ($formLogin->isValid($posts)) {

                //$valuesUnfiltered = $formLogin->getUnfilteredValues();
                //$this->authLogin($valuesUnfiltered);

                $values = $formLogin->getValues();
                $this->authLogin($values);

            } else {
                $errors = $formLogin->getMessages();
                foreach ($errors as $name => $m) {
                    $message .= nl2br($name . ' : ' . implode(PHP_EOL, $m) . PHP_EOL);
                }

                $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
                $flashMessenger->setNamespace('login')->addMessage($message);
            }
        }

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_forword('index');
        } else {
            $formLogin = $this->getFormUserLogin();
            $this->view->formLogin = $formLogin;
        }
    }

    public function logoutAction()
    {
        $namespaces = Kbs::initConfig('Session')->namespace;

        require_once('Extension/Session.php');
        Extension_Session::namespaceUnset($namespaces->auth->dbTable);
        Extension_Session::namespaceUnset($namespaces->acl);

        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_forward('login');
    }

    public static function authLogin($data)
    {
        $message = '';
        $namespace = 'login';

        $authAdapterDbTable = Zend_Registry::get('authAdapterDbTable');
        $authAdapterDbTable->setIdentity($data['userLogin'])->setCredential($data['userPass']);

        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($authAdapterDbTable);

        if ($result->isValid()) {
            if ($data['remember']) {
                Extension_Session::rememberMe();
            }
            $data = $authAdapterDbTable->getResultRowObject(null, 'user_pass');
            $auth->getStorage()->write($data);
            $namespace = 'index';
        }

        $message = implode('<br />', $result->getMessages() );

        require_once('Zend/Controller/Action/HelperBroker.php');
        $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
        $flashMessenger->setNamespace($namespace)->addMessage($message);
        
        $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');
        $redirector->gotoUrlAndExit('/admin/user');
    }


    public function getFormUserLogin()
    {
        $cache = Kbs::initCache('FormUserLogin');
        if ($cache) {
            $id = $cache->id . Kbs::initLocale();
            $formUserLogin = $cache->load($id);
            if(false == $formUserLogin) {
                $formUserLogin = self::makeFormUserLogin();
                $cache->save($formUserLogin->render(), $id, $cache->tags);
            }
        } else {
            $formUserLogin = self::makeFormUserLogin();
        }

        return $formUserLogin;
    }


    public static function makeFormUserLogin()
    {
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $view = $viewRenderer->view;
        
        require_once('Extension/Form.php');
        $formUserLogin = new Extension_Form();

        $formUserLogin->setAction($view->U('user', 'login'));
        $formUserLogin->setMethod(Zend_Form::METHOD_POST);
        $formUserLogin->setName('formLogin');

        require_once('Zend/Form/Element.php');
        $formUserLogin->addElementPrefixPath('Extension_Form_Decorator', 'Extension/Form/Decorator', Zend_Form_Element::DECORATOR);
        $formUserLogin->addElementPrefixPath('Extension_Form_Filter', 'Extension/Form/Filter', Zend_Form_Element::FILTER);
        $formUserLogin->addElementPrefixPath('Extension_Form_Validate', 'Extension/Form/Validate', Zend_Form_Element::VALIDATE);
        $formUserLogin->setElementFilters(array('StringTrim'));
        $view->placeholder('body_onload')->set("document.getElementById('formLogin').userLogin.focus();");

        $ajaxUrl = $view->U('user', 'check-login', 'ajax', array('login' => ''));

        require_once('Zend/Form/Element/Text.php');
        $fieldUsername = new Zend_Form_Element_Text('userLogin');
        $fieldUsername->setRequired(true);
        $fieldUsername->setLabel('User Login');
        $fieldUsername->setDescription("* required");
        $fieldUsername->setOptions(array(
            'onkeyup'  => "checkUserLogin('checkUserLoginMessage', '" . $ajaxUrl . "', this.value)",
            'class'    => 'input',
            'tabindex' => '10',
        ));
        $fieldUsername->setAttrib('maxLength', 64);
        $fieldUsername->addDecorators(array(
            array('ViewHelper'),
            array('Errors'),
            array('HtmlTag',     array('tag'    => 'p')),
            array('Label',       array('tag'    => 'dt')),
            array('Description', array('id'     => 'checkUserLoginMessage', 
                                       'escape' => false, 
                                       'tag'    => 'span')),
        ));
        $fieldUsername->addFilter('Login');
        $fieldUsername->addValidators(array(
            array('Login',        true),
            array('NotEmpty',     true),
            array('alnum',        true),
            array('StringLength', false, array(3, 64)),
            array('regex',        false, array('/^[a-z]/i')),
        ));

        require_once('Zend/Form/Element/Password.php');
        $fieldPassword = new Zend_Form_Element_Password('userPass');
        $fieldPassword->setRequired(true);
        $fieldPassword->setOptions(array('class'    => 'password', 'tabindex' => '20',));
        $fieldPassword->setAttrib('maxLength', 64);
        $fieldPassword->setDescription('* required');
        $fieldPassword->setLabel('User Password');
        $fieldPassword->addValidator('StringLength', false, array(3));
        $fieldPassword->addDecorators(array(
            array('ViewHelper'),
            array('Errors'),
            array('HtmlTag',     array('tag'    => 'p')),
            array('Label',       array('tag'    => 'dt')),
            array('Description', array('tag'    => 'span')),
        ));

        require_once('Zend/Form/Element/Checkbox.php');
        $fieldRemember = new Zend_Form_Element_Checkbox('remember');
        //$fieldRemember->setLabel('Remember Me');
        $fieldRemember->setDescription('Remember Me');
        $fieldRemember->setOptions(array('class' => 'options',
                                         'tabindex' => '30',));
        $fieldRemember->addDecorators(array(
            array('ViewHelper'),
            array('Errors'),
            array('HtmlTag',     array('tag'    => 'dt')),
            //array('Label',       array('tag'    => 'dt')),
            array('Description', array('tag'    => 'span')),
        ));

        require_once('Zend/Form/Element/Hidden.php');
        $fieldToken = new Zend_Form_Element_Hidden('token');
        $fieldToken->setValue(md5($_SERVER['HTTP_USER_AGENT']));

        require_once('Zend/Form/Element/Reset.php');
        $fieldReset = new Zend_Form_Element_Reset('reset');
        $fieldReset->setAttrib('style', 'width:100px');
        
        require_once('Zend/Form/Element/Hash.php');
        $fieldHash = new Zend_Form_Element_Hash('no_csrf_token');
        $fieldHash->setSalt('unique');
 
        require_once('Zend/Form/Element/Submit.php');
        $fieldSubmit = new Zend_Form_Element_Submit('submitted');
        $fieldSubmit->setLabel('Log In');
        $fieldSubmit->setOptions(array('class' => 'submit',
                                       'tabindex' => '100',
                                       'style' => 'width:100px'));


        $fieldUsername->setOrder(1);
        $fieldPassword->setOrder(3);
        $fieldRemember->setOrder(5);
        $fieldToken->setOrder(7);
        $fieldReset->setOrder(9);
        $fieldHash->setOrder(11);
        $fieldSubmit->setOrder(15);

        $formUserLogin->addElement($fieldUsername);
        $formUserLogin->addElement($fieldPassword);
        $formUserLogin->addElement($fieldRemember);
        $formUserLogin->addElement($fieldToken);
        $formUserLogin->addElement($fieldReset);
        ####$formUserLogin->addElement($fieldHash);
        $formUserLogin->addElement($fieldSubmit);
        
        $formUserLogin->setDefaults(array('userLogin' => '', 'userPass' => ''));

        /*
        $formUserLogin->addDisplayGroup(
            array('userLogin', 'userPass', 'userOptions'), 
            'groupLogin', 
            array('displayGroupClass' => 'Extension_Form_DisplayGroup')
        );
        */

        /*
        $subForm = new Zend_Form();
        $subForm->addElement('Text', 'subFormTitle', array('value' => 'sub', 'disabled' => 'disabled'));
        $formUserLogin->addSubForm($subForm, 'subForm');
        $formUserLogin->setSubFormDecorators(
            array('FormElements', 'Fieldset')
        );
        */

        $formUserLogin->addDisplayGroupPrefixPath('Extension_Form_Decorator', 'Extension/Form/Decorator/');
        $formUserLogin->setDisplayGroupDecorators(array(
            'FormElements',
            'Fieldset',
        ));

        //var_dump($formUserLogin->userPass);
        //var_dump($formUserLogin->getElement('userPass'));
        //var_dump($formUserLogin->getDisplayGroup('groupLogin'));

        return $formUserLogin;
    }


}